<?php
class Comment_model extends CI_Model {
	function __construct()
    {
        parent::__construct();
    }
    /**
     * 获取某个个体的相关评论
     * @param int $target_id
     * @param int $target_type
     * @param int $offset
     * @param int $limit
     */
	public function find_by_target_id($target_id, $target_type, $offset = 0, $limit = 10) {
//		$this->db->where('target_id', intval($target_id));
//		$this->db->where('target_type', $target_type);
//		if (!empty($offset) && !empty($limit)) {
//			$this->db->limit($offset, $limit);
//		}
//return $this->db->get('comments')->result_array();
		$sql = "select c.*,u.nickname from comments c left join users u on u.id=c.created_by
				where target_id=" . intval($target_id). " and target_type=" . $this->db->escape($target_type) .
				" limit " . $offset . "," . $limit;
		return $this->db->query($sql)->result_array();
		
	}
	
	/**
	 * 获取某个评论对象的个数
	 * @param int $target_id
	 * @param int $target_type
	 */
	public function get_count_by_target_id($target_id, $target_type) {
		$this->db->where('target_id', intval($target_id));
		$this->db->where('target_type', $target_type);
		$this->db->from('comments');
		return $this->db->count_all_results();
	}
	/**
	 * 添加评论
	 * @param array $data
	 */
	public function add($data) {
		$this->db->insert("comments", $data);
		return $this->db->insert_id();
	}
	
	/**
	 * 获取某个对象被评论的平均分
	 * @param unknown_type $target_id
	 * @param unknown_type $target_type
	 */
	public function get_average_score($target_id, $target_type) {
		$sql = " select avg(score) as score from comments where target_id=" . intval($target_id) . " and target_type=" .
				$this->db->escape($target_type);
		$result = $this->db->query($sql);
		$row = $result->row_array();
		$result->free_result();
		return $row['score'];
	}
	
	/**
	 * 获取某个对象被评论的平均分
	 * @param array $target_ids
	 * @param string $target_type
	 */
	public function find_average_score($target_ids, $target_type) {
		$sql = " select target_id,avg(score) as score from comments where target_id in (" . $target_ids . ") and target_type=" .
				$this->db->escape($target_type) . " group by target_id";
		$result = $this->db->query($sql)->result_array();
		return $result;
	}
}